package com.neusoft.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neusoft.domain.Category;
import com.neusoft.domain.Food;
import com.neusoft.domain.ResultPage;
import com.neusoft.domain.vo.FoodVo;
import com.neusoft.mapper.CategoryMapper;
import com.neusoft.mapper.FoodMapper;
import com.neusoft.service.FoodService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResultPage<FoodVo> findFoodByPage(Integer page, Integer pageSize, String foodName, Integer businessId) {
        // 1. 调用一个或者多个dao层方法,实现业务逻辑处理
        PageHelper.startPage(page,pageSize);
        List<Food> foodList = foodMapper.selectFoodByFoodName(foodName,businessId);

        List<FoodVo> foodVoList = new ArrayList<>();
        for (Food food : foodList) {

            FoodVo foodVo = new FoodVo();
            //对象拷贝
            BeanUtils.copyProperties(food,foodVo);
            // 根据categoryId查询分类信息
            Category category = categoryMapper.selectById(food.getCategoryId());
            // 健壮性判断
            if(category != null){
                foodVo.setCategoryName(category.getCategoryName());
            }
            foodVoList.add(foodVo);
        }

        PageInfo<Food> pageInfo = new PageInfo<>(foodList);
        // 2.响应数据给controller层调用位置
        return new ResultPage(foodVoList,pageInfo.getTotal());
    }

    @Override
    public void saveFood(Food food) {
        // 1. 调用一个或者多个dao层方法,实现业务逻辑处理
        foodMapper.insert(food);
    }

    @Override
    public void updateFood(Food food) {
        // 1. 调用一个或者多个dao层方法,实现业务逻辑处理
        foodMapper.update(food);
    }
}
